// pages/goods/index.js
import { request } from "../../request/index.js"
Page({

    /**
     * 页面的初始数据
     */
    data: {
     goods:[],
     GoodsInfo:{},
     isColl:false
    },
   async getGoods(goods_id){
    const goods=await request({
          url:"/goods/detail",
          data:{goods_id}
      })
      this.GoodsInfo=goods;
      this.setData({
        goods:{
            data:{
              message:{
                goods_name:goods.data.message.goods_name,
                goods_price:goods.data.message.goods_price,
                goods_introduce:goods.data.message.goods_introduce.replace(/\.webp/g,'.jpg'),
                pics:goods.data.message.pics
              }
            }
          }
      })
    },
    openImg(e){
      console.log(e);
      const urls=this.GoodsInfo.data.message.pics.map((v)=>v.pics_mid)
      const current=e.currentTarget.dataset.url
      wx.previewImage({
        current:current,
        urls:urls
      })
    },
    add(){
      let cart=wx.getStorageSync('cart') ||[]
      let index=cart.findIndex(v=>v.data.message.goods_id===this.GoodsInfo.data.message.goods_id)
      if(index===-1){
        this.GoodsInfo.num=1;
        this.GoodsInfo.checked=true
        cart.push(this.GoodsInfo)
      }else{
        cart[index].num++;
      }
      wx.setStorageSync('cart', cart);
      wx.showToast({
        title: '加入成功',
        icon:"success",
        mask:true
      })
    },
    coll(){
     let isColl=false
     let coll=wx.getStorageSync('coll') ||[]
     let index=coll.findIndex((v)=>v.data.message.goods_id===this.GoodsInfo.data.message.goods_id)
     if(index !==-1){
       coll.splice(index,1)
       isColl=false
       wx.showToast({
         title: '取消成功',
         icon:"success",
        mask:true
       })
     }else{
       coll.push(this.GoodsInfo)
       isColl=true
       wx.showToast({
        title: '收藏成功',
        icon:"success",
       mask:true
      })
     }
     wx.setStorageSync('coll', coll)
    },
    money(){
     
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
    console.log(options);
    let {goods_id}=options
    this.getGoods(goods_id)
    }, 

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
      // let pages=getCurrentPages()
      // let currentPage=pages[pages.length-1]
      // let options=currentPage.options
      // const {goods_id}=options
      // this.getGoods(goods_id)
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})